<template>
  <div class="news-add-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-2xl font-bold text-gray-900">新增新闻</h1>
        </div>
        <div class="flex space-x-3">
          <el-button type="info" @click="handlePreview" class="w-[90px]">
            预览
          </el-button>
          <el-button type="success" @click="handleSave" :loading="saving" class="w-[90px]">
            保存
          </el-button>
          <el-button type="default" @click="handleCancel" class="w-[90px]">
            取消
          </el-button>
        </div>
      </div>
    </div>

    <!-- 使用共享的新闻表单组件 -->
    <div class="form-container">
      <NewsForm
        ref="newsFormRef"
        mode="add"
      />
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import NewsForm from '~/components/admin/NewsForm.vue'
import { adminNewsAPI } from '~/services/api'

// 定义页面布局
definePageMeta({
  layout: 'admin'
})

const router = useRouter()
const newsFormRef = ref()
const saving = ref(false)

// 保存新闻
const handleSave = async () => {
  try {
    saving.value = true
    
    // 验证表单
    const valid = await newsFormRef.value?.validate()
    if (!valid) return
    
    // 获取表单数据
    const formData = newsFormRef.value?.formData
    
    // 调用后端API保存新闻
    await adminNewsAPI.addNews(formData)
    
    ElMessage.success('新闻保存成功')
    router.push('/admin/news/list')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    saving.value = false
  }
}

// 预览新闻
const handlePreview = () => {
  newsFormRef.value?.handlePreview()
}

// 删除新闻（新增页面不应该有删除操作，但为了兼容性保留）
const handleDelete = async (newsId) => {
  ElMessage.warning('新增页面不支持删除操作')
}

// 取消操作
const handleCancel = async () => {
  // 检查是否有未保存的内容
  const formData = newsFormRef.value?.formData
  const hasContent = formData?.title || formData?.summary || formData?.content
  
  if (hasContent) {
    try {
      await ElMessageBox.confirm(
        '当前有未保存的内容，确定要离开吗？',
        '确认离开',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
    } catch {
      return
    }
  }
  
  router.push('/admin/news/list')
}
</script>

<style scoped>
.news-add-page {
  @apply min-h-screen bg-gray-50;
}

.page-header {
  @apply bg-white shadow-sm border-b border-gray-200 px-6 py-4 mb-6;
}

.form-container {
  @apply px-6 pb-6;
}
</style>